package com.robot.interceptors;


import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.robot.common.result.Response;
import com.robot.common.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: jwt拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    /**
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     * @Description HandlerInterceptor 中的方法，重写它来自定义拦截逻辑
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*
         *针对跨域请求种类 OPTIONS，设置成 "SC_OK" 以允许请求方法
         * 下一步操作应当检查token是否存在。
         */
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");

        //从请求头中获取到前端 Vue 发起的 token
        String token = request.getHeader("Authorization");
        if (token != null) {
            boolean result = JwtTokenUtil.verify(token);
            if (result) {
                System.out.println("通过拦截器");
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            //使用 fastjson 创建 JSON 对象
            JSONObject json = new JSONObject();
            json.put("msg", "请先登录");
            json.put("code", "40001");
            //返回易于 Vue 接受的信息，并说明发生的错误（如果有）
            response.getWriter().append(json.toString());
            System.out.println("认证失败，未通过拦截器!!!");

        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
            return false;
        }
        return false;
    }



    /**
     * 校验JWT
     *
     * @param request
     * @param response
     * @param url
     * @return
     * @throws Exception
     */
    public boolean checkJwt(HttpServletRequest request, HttpServletResponse response, String url) throws Exception {
        String authToken = request.getHeader("Authorization");
        if (StringUtils.isBlank(authToken)) {
            return checkError(response, url);
        }
        JwtTokenUtil.verify(authToken);
        return true;
    }

    /**
     * 校验失败
     *
     * @param response
     * @param url
     * @return
     * @throws Exception
     */
    public boolean checkError(HttpServletResponse response, String url) throws Exception {
        response.setHeader("Content-Type", "application/json");
        response.setCharacterEncoding("UTF-8");
        log.error("当前接口-{}需要登录!", url);
        response.getWriter().print(JSON.toJSONString(Response.error( 40001,"Token校验失败，当前请求需要登录！！！")));
        return false;
    }



}

